import java.io.IOException;
import java.util.ArrayList;

public class CircularShifter extends Filter{
    //单词的列表
    private ArrayList<String> wordlist = new ArrayList<String>();
    //重组后的行的列表
    private ArrayList<String> linelist = new ArrayList<String>();

    CircularShifter(Pipe input, Pipe output){
        super(input, output);
    }

    @Override
    protected void transform() throws IOException {
        String templine = "";
        //读数据
        while((templine = input.readerLine()) != null){
            //将数据拆分为不同单词
            this.lineSplitWord(templine);
            //将单词重组为句子
            this.recombination();
            //输出重组结果
            for(int i = 0; i < linelist.size(); i++){
                //System.out.println("linelist:" + linelist.get(i));
                output.writerLine(linelist.get(i));
            }
            //清空wordlist、linelist和templine
            wordlist.clear();
            linelist.clear();
            templine = "";
        }
        input.closeReader();
        output.closeWriter();
    }
    //从一行中提取单词存入单词表中
    private void lineSplitWord(String line){
        String word = "";
        int i = 0;
        while(i < line.length()){
            if(line.charAt(i) != ' '){
                word += line.charAt(i);
            }
            else{
                wordlist.add(word);
                word = "";
            }
            i++;
        }
        if (word.length() > 0) {
            wordlist.add(word);
        }
    }

    private void recombination(){
        for(int j = 0; j < wordlist.size(); j++){
            String templine = "";
            for (int k = wordlist.size() - 1 - j; k < wordlist.size(); k++){
                templine += wordlist.get(k) + " ";
            }
            for (int m = 0; m < wordlist.size() - 1 - j; m++){
                if(m != wordlist.size() - j - 2){
                    templine += wordlist.get(m) + " ";
                }
                else{
                    templine += wordlist.get(m);
                }
            }
            linelist.add(templine);
        }
    }
}